package com.lmoumou.lib_pdfload

import android.annotation.SuppressLint
import android.os.Build
import android.text.TextUtils
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import com.lmoumou.lib_pdfload.code.BASE64Encoder
import com.lmoumou.lib_pdfload.view.ProgressListener
import java.io.UnsupportedEncodingException

/**
 * @author Lmoumou
 * @date : 2019/8/27 15:38
 */
object  WebViewHelper {
    @SuppressLint("SetJavaScriptEnabled")
    fun webViewSetting(webView: WebView) {
        webViewSetting(webView, null)
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun webViewSetting(webView: WebView, listener: ProgressListener?) {
        val settings = webView.settings
        settings.savePassword = false
        settings.javaScriptEnabled = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.allowFileAccessFromFileURLs = true
            settings.allowUniversalAccessFromFileURLs = true
        }
        settings.setSupportZoom(true)
//        settings.builtInZoomControls = true
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }
        }
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)

                listener?.LoadProgress(newProgress)
            }
        }
    }

    fun webViewLoadPDF(webView: WebView, docPath: String) {
        var docPathCopy = docPath
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//api >= 19
            webView.loadUrl("file:///android_asset/pdf/pdf.html?$docPathCopy")
        } else {
            if (!TextUtils.isEmpty(docPathCopy)) {
                var bytes: ByteArray? = null
                try {// 获取以字符编码为utf-8的字符
                    bytes = docPathCopy.toByteArray(charset("UTF-8"))
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }

                if (bytes != null) {
                    docPathCopy = BASE64Encoder().encode(bytes)// BASE64转码
                }
            }
            webView.loadUrl("file:///android_asset/pdf/pdf.html?$docPathCopy")
        }
    }

}